package com.maxiaowei.controller;

import com.maxiaowei.pojo.Users;
import com.maxiaowei.pojo.bo.UserBO;
import com.maxiaowei.service.UserService;
import com.maxiaowei.util.CookieUtils;
import com.maxiaowei.util.CustomJSONResult;
import com.maxiaowei.util.JsonUtils;
import com.maxiaowei.util.MD5Utils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述:
 * <p>
 * 作者: maxiaowei
 */
@Tag(name = "注册登录", description = "用于注册登录的相关接口")
@RestController
@RequestMapping("passport")
public class PassportController {

    @Autowired
    public UserService userService;

    @Operation(
            summary = "判断用户名是否存在",
            description = "根据用户名判断用户是否存在",
            parameters = {
                    @Parameter(name = "username", description = "用户名", example = "ZhangSan", required = true)
            },
            method = "GET"
    )
    @GetMapping("/usernameIsExist")
    public CustomJSONResult usernameIsExist(String username, HttpMethod httpMethod) {
        // 1. 判断用户名不能为空
        if (StringUtils.isBlank(username)) {
            return CustomJSONResult.errorMsg("username cannot be blank");
        }
        // 2. 查找注册的用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist) {
            return CustomJSONResult.errorMsg("username already exist");
        }
        // 3. 请求成功，用户名没有重复
        return CustomJSONResult.ok();
    }

    @Operation(
            summary = "注册接口",
            description = "用户注册",
            parameters = {
                    @Parameter(name = "userBO", description = "前端返回后端用户信息")
            }
    )
    @PostMapping("/register")
    public CustomJSONResult register(@RequestBody UserBO userBO,
                                     HttpServletRequest request,
                                     HttpServletResponse response) {
        String username = userBO.getUsername();
        String password = userBO.getPassword();
        String confirmPwd = userBO.getConfirmPassword();

        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password) ||
                StringUtils.isBlank(confirmPwd)) {
            return CustomJSONResult.errorMsg("username or password cannot be blank");
        }

        // 1. 查询注册的用户名是否存在
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist) {
            return CustomJSONResult.errorMsg("username already exist");
        }

        // 2. 密码长度不能少于6位
        if (password.length() < 6) {
            return CustomJSONResult.errorMsg("password must be at least 6 characters");
        }

        // 3. 判断两次密码是否一致
        if (!password.equals(confirmPwd)) {
            return CustomJSONResult.errorMsg("password and confirm password do not match");
        }

        // 4. 实现注册
        Users userResult = userService.createUser(userBO);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(userResult), true);

        return CustomJSONResult.ok(userResult);
    }

    @Operation(
            summary = "用户登录",
            description = "用户登录",
            method = "POST"
    )
    @PostMapping("/login")
    public CustomJSONResult login(@RequestBody UserBO userBO,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        String username = userBO.getUsername();
        String password = userBO.getPassword();
        // 0. 判断用户名和密码必须不为空
        if (StringUtils.isBlank(username) ||
                StringUtils.isBlank(password)) {
            return CustomJSONResult.errorMsg("username or password cannot be blank");
        }
        // 1. 实现登录
        Users userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));
        if (userResult == null) {
            return CustomJSONResult.errorMsg("username or password does not exist");
        }
        userResult = setNullProperty(userResult);
        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(userResult), true);
        // TODO 生成用户token，存入redis会话
        // TODO 同步购物车数据
        return CustomJSONResult.ok(userResult);
    }

    /**
     * 敏感信息忽略
     *
     * @param userResult
     * @return
     */
    private Users setNullProperty(Users userResult) {
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        return userResult;
    }

    @Operation(summary = "用户退出登录", description = "用户退出登录", method = "POST")
    @PostMapping("/logout")
    public CustomJSONResult logout(@RequestParam String userId,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {
        // 清除用户的相关信息的cookie
        CookieUtils.deleteCookie(request, response, "user");

        // TODO 用户退出登录，需要清空购物车
        // TODO 分布式会话中需要清除用户数据

        return CustomJSONResult.ok();
    }


}
